<?php


namespace Api\Controller;


/** 
 * [站内信接口]
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */
class MailController extends UserBaseController 
{
	// 发送一条私信给一个用户
	// nickname  msg
	public function sendToUser()
	{
		$nickname = I('nickname', '', 'trim');
		$msg = I('msg', '', 'trim');
		if (!$nickname || !$msg) $this->param_error();
		$target_id = event('User')->getUser($nickname);
		if (!$target_id) $this->error(self::$API_ERROR['USER'], '用户信息有误');
		if ($target_id == UID) $this->error(self::$API_ERROR['MAIL_TO_SELF'], '不能发送给自己');
		$res = event('Mail')->send(UID, $target_id, $msg);
		$res ? $this->success('发送成功') : $this->error(self::$API_ERROR['ERROR_MAIL'], '发送失败');
	}

	// 最新的私信的朋友的列表   按照p 页码分页  每页默认10个
	public function friends($p = 1, $pager = 10)
	{
		$event = event('Mail');
		$mail_friends = $event->getFriendsList(UID, $p, $pager);
		if ($mail_friends)
		{
			// $fids = array_column($mail_friends, 'uid');
			// $friends = array_column(event('User')->userList($fids), null, 'uid');
			foreach ($mail_friends as &$value) {
				$value['user'] 		= event('User')->info($value['uid']);//$friends[$value['uid']];
				unset($value['uid'], $value['user']['uid']);
			}
		}
		return $this->list_success($mail_friends);
	}

	/** 
	 * [跟某个朋友的私信信息]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param $nickname 朋友的昵称  $timestamp  用时间戳分页
	 * @return 
	 */
	public function msg()
	{
		$nickname = I('nickname', '', 'trim');
		if (!$nickname) $this->param_error();
		$target_id = event('User')->getUser($nickname);
		if (!$target_id) $this->error(self::$API_ERROR['USER'], '用户信息有误');
		$list = event('Mail')->lists(UID, $target_id, I('timestamp', 0, 'intval'));
		$list = field_filter($list, ['uid', 'target_id', 'content', 'send_time'], true);
		foreach ($list as &$value) {
			$value['mine'] = $value['uid'] == UID ? 1 : 0;
			unset($value['uid'], $value['target_id']);
		}

		#TODO 更新对话的读取时间
		event('Mail')->setRead(UID, $target_id);

		$this->list_success($list);
	}


}